<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { userPasswordUpdateService } from '@/api/user.js';
import { useUserInfoStore } from '@/stores/userInfo.js';
import { useTokenStore } from '@/stores/token.js';
import { useRouter } from 'vue-router';

const userInfoStore = useUserInfoStore();
const tokenStore = useTokenStore();
const router = useRouter();

const userPwd = ref({
    oldPwd: '',
    newPwd: '',
    rePwd: ''
});

// 定义校验密码的函数
const checkPassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入确认新密码'));
    } else if (value !== userPwd.value.newPwd) {
        callback(new Error('两次密码输入不一致'));
    } else {
        callback();
    }
};

const rules = {
    oldPwd: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 5, max: 16, message: '原密码长度在5-16位之间', trigger: 'blur' }
    ],
    newPwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '新密码长度在5-16位之间', trigger: 'blur' }
    ],
    rePwd: [
        { validator: checkPassword, trigger: 'blur' }
    ]
};

const updateUserPwd = async () => {
    const params = {
        old_pwd: userPwd.value.oldPwd,
        new_pwd: userPwd.value.newPwd,
        re_pwd: userPwd.value.rePwd
    };
    let result = await userPasswordUpdateService(params, tokenStore.token);
    ElMessage.success(result.message ? result.message : '修改成功');
    userInfoStore.setInfo(result.data);
    router.push('/user/login');
    // if (result.code === '0') {
    //     ElMessage.success('修改成功');
    //     userInfoStore.setInfo(result.data);
    //     router.push('/user/login');
    // } else {
    //     ElMessage.error(result.message ? result.message : '修改失败');
    // }
};
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>修改密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form :model="userPwd" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="原密码" prop="oldPwd">
                        <el-input v-model="userPwd.oldPwd" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPwd">
                        <el-input v-model="userPwd.newPwd" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="rePwd">
                        <el-input v-model="userPwd.rePwd" type="password"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updateUserPwd">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>